package com.example.jdk11;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * JEP 321 HTTP Client (Standard) : https://openjdk.org/jeps/321
 * 该提案旨在引入一个新的 HTTP 客户端 API 到 Java 标准库以取代陈旧的 HttpURLConnection类。
 * 目标是为处理 HTTP 请求和响应提供更现代、灵活的 API。
 * HTTP 客户端 API 是在 Java 11 中正式发布的，关键特性和改进包括：
 * 1. 异步 API ：HTTP客户端API支持异步操作，允许开发人员异步发送请求和接收响应，从而提高应用程序性能；
 * 2. HTTP/2 支持 ：新 API 支持 HTTP/2 协议；
 * 3. WebSocket 支持 ：API 包括对 WebSocket 通信的内置支持，使得使用 WebSocket 协议更加方便；
 * 4. 响应体处理 ：API 提供了更多处理响应体的灵活性，包括对响应流进行反应式编程的支持；
 *
 */
public class HttpClientTest {

    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException, ExecutionException {
        //syncHttpGetExample();
        asyncHttpPostExample();
    }

    /**
     * GET 同步请求
     * @throws URISyntaxException
     * @throws IOException
     * @throws InterruptedException
     */
    private static void syncHttpGetExample() throws URISyntaxException, IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        URI uri = new URI("https://www.baidu.com");
        HttpRequest request = HttpRequest.newBuilder()
                .uri(uri)
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("Status Code: " + response.statusCode());
        System.out.println("Response Body " + response.body());
    }

    /**
     * 异步POST请求
     * @throws URISyntaxException
     * @throws ExecutionException
     * @throws InterruptedException
     */
    private static void asyncHttpPostExample() throws URISyntaxException, ExecutionException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        String jsonRequestBody = "{\"title\":\"java\",\"content\":\"java\",\"author\":\"jun\"}";
        URI uri = new URI("http://localhost:32001/consumer/message/msg");
        HttpRequest request = HttpRequest.newBuilder()
                .uri(uri)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();
        CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        HttpResponse<String> response = futureResponse.get();
        System.out.println("Status Code: " + response.statusCode());
        System.out.println("Response Body: " + response.body());
    }
}
